using System.Windows.Controls;
using StockholmsStad.Windows.UI.Modules.Minister.Controls;
using StockholmsStad.Windows.UI.Modules.Minister.Interfaces;
using StockholmsStad.Windows.UI.Modules.Minister.Models;

namespace StockholmsStad.Windows.UI.Modules.Minister.Views
{
    /// <summary>
    /// Interaction logic for MinisterDetailsView.xaml
    /// </summary>
    public partial class MinisterDetailsView : IMinisterDetailsView
    {
        private readonly IMinisterService ministerService;

        public MinisterDetailsView(IMinisterService service)
        {
            ministerService = service;
            InitializeComponent();

            Loaded += MinisterDetailsView_Loaded;

            InitializeControls();
        }

        private void MinisterDetailsView_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var model = DataContext as MinisterPresentationModel;
            if (model == null)
                Model = ministerService.AddNewMinister();
        }

        private void InitializeControls()
        {
            var ministerControl = new MinisterDetailsControl(ministerService);
            GroupBoxMinister.Content = ministerControl;
        }

        #region IMinisterDetailsView Members

        public MinisterPresentationModel Model
        {
            get { return DataContext as MinisterPresentationModel; }
            set { DataContext = value; }
        }

        #endregion

        private void GroupBoxMinister_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (e.OriginalSource.GetType() == typeof(Button))
            {
                var button = (Button) e.OriginalSource;

                if (button.Name == "AddButton")
                {
                    Model = ministerService.AddNewMinister();
                }

                if (button.Name == "CancelButton")
                {
                    Model = Model.MinisterId.HasValue ? ministerService.GetMinister(Model.MinisterId.Value) : ministerService.AddNewMinister();
                }
            }

            e.Handled = true;
        }
    }
}
